package com.txby.pf.common.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

public class TreeUtil {
	
	/**
	 * @param dataSource list数据源
	 * @param id	层级结构id	
	 * @param pId	父级节点id
	 * @return	
	 */
	public static LinkedHashMap<String,HashMap> getTreeData(List<HashMap> dataSource,String id,String pId)
	{
		LinkedHashMap returnMap = new LinkedHashMap();
		HashMap<String,String> root = new HashMap<String,String>();
		root.put(id, "");
		assembleTree(dataSource,root,id,pId,1);
		returnMap.put("root",root);
		
		return returnMap;
	}
	
	public static void assembleTree(List<HashMap> dataSource,HashMap node ,String id,String pId,Integer level)
	{
		List childList = getChildList(dataSource,node,id,pId);
		node.put("children", childList);
		if(childList.size() > 0)
		{
			for(int i = 0 ; i<childList.size(); i++ )
			{
				HashMap child = (HashMap)childList.get(i);
				child.put("level", level);
				assembleTree(dataSource,child,id,pId,level+1);
			}
		}
	}
	
	/**
	 * 得到子节点列表
	 */
	private static List getChildList(List<HashMap> dataSource,HashMap node,String id, String pId )
	{
		List childList = new ArrayList();
		for (int i = 0; i < dataSource.size() ; i++) 
		{
			HashMap child = (HashMap)dataSource.get(i);
			String dictId = node.get(id).toString();
			String dictPId = child.get(pId).toString();
			if (dictId.equals(dictPId))
			{
				childList.add(child);
				dataSource.remove(i);
				i--;
			}
		}
		return childList;
	}
}